#!/bin/bash
# /**
# * Copyright (c) 2018, God's harbor
# * All rights reserved.
# * @file    arrange_file.sh
# * @brief   代码整理的神器，可以一次性将某个目录下的C语言源码整理成格式化,该神器依赖vim的格式化插件
# * @author  Jason Zhou,yzfcer@163.com
# * @version 1.0
# * @date    2021-09-15
# */

filename=$1;
file_cnt=0
function format_file()
{
    filename=$1;
    file_cnt=$[$file_cnt+1]
    echo "format_file:"$filename
    if [ ! -f $filename ]
    then
        echo "error:file \""${filename}"\" is not exist"
        exit
    fi
    dos2unix $filename
    vim $filename -c FormatCodeExit
}

function format_directory()
{
    filelist=`find ${1} -name "*.cpp"`
    for file in $filelist
    do
        format_file $file
    done

    filelist=`find ${1} -name "*.c"`
    for file in $filelist
    do
        format_file $file
    done

    filelist=`find ${1} -name "*.h"`
    for file in $filelist
    do
        format_file $file
    done

    filelist=`find ${1} -name "*.jsn"`
    for file in $filelist
    do
        format_file $file
    done
}

function usage()
{
    echo "arrangeIfile.sh uasge:"
    echo "arrangeIfile.sh <directory>"
    echo "directory must be a C-style code directory"
}

function main()
{
    if [ $# -lt 1 ]
    then
        echo "miss argument"
        usage
        exit
    fi

    echo "Arg1="$1

    #delete switch files and cscope files
    start_time=$(date "+%Y-%m-%d %H:%M:%S")
    echo "delete switch files"
    find $1 -name *.swp | xargs rm -rf
    find $1 -name *.swo | xargs rm -rf
    find $1 -name *.swn | xargs rm -rf

    echo "delete cscope files"
    find $1 -name cscope.* | xargs rm -rf

    format_directory $1

    end_time=$(date "+%Y-%m-%d %H:%M:%S")
    echo "start_time:"$start_time
    echo "end_time  :"$end_time
    echo "file_cnt  :"$file_cnt

}
main $@
